import 'package:flutter/material.dart';
import 'dart:math';

class AnimatedTextList extends StatefulWidget {
  final List<String> texts;
  final double containerHeight;
  final double containerWidth;
  final Duration waitDuration;
  final TextStyle? textStyle;
  final VoidCallback? onAnimationComplete;
  final bool isLoop;
  final Duration? cyclePauseDuration;
  final double minFontSize;
  final double maxFontSize;
  final bool enableRotation;

  const AnimatedTextList({
    Key? key,
    required this.texts,
    required this.containerHeight,
    required this.containerWidth,
    this.waitDuration = const Duration(seconds: 3),
    this.textStyle,
    this.onAnimationComplete,
    this.isLoop = false,
    this.cyclePauseDuration = const Duration(milliseconds: 500),
    this.minFontSize = 12.0,
    this.maxFontSize = 24.0,
    this.enableRotation = true,
  }) : super(key: key);

  @override
  State<AnimatedTextList> createState() => _AnimatedTextListState();
}

class _AnimatedTextListState extends State<AnimatedTextList>
    with TickerProviderStateMixin {
  late List<AnimationController> _fadeInControllers;
  late List<AnimationController> _slideUpControllers;
  late List<AnimationController> _fadeOutControllers;
  late List<Animation<double>> _fadeInAnimations;
  late List<Animation<Offset>> _slideUpAnimations;
  late List<Animation<double>> _fadeOutAnimations;
  late List<Animation<Offset>> _slideOutAnimations;
  late List<Animation<double>> _rotationAnimations;
  
  late List<double> _horizontalPositions;
  late List<double> _verticalSpacings;
  late List<double> _finalVerticalPositions;
  late List<double> _fontSizes;
  late List<double> _initialRotations;
  
  final Random _random = Random();
  bool _isAnimatingIn = false;
  bool _isWaiting = false;
  bool _isAnimatingOut = false;
  bool _isDisposed = false;
  bool _isResetting = false;
  bool _shouldShow = false;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _generateRandomPositions();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      _startAnimation();
    });
  }

  void _initializeAnimations() {
    _fadeInControllers = List.generate(
      widget.texts.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 800),
        vsync: this,
      ),
    );

    _slideUpControllers = List.generate(
      widget.texts.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 800),
        vsync: this,
      ),
    );

    _fadeOutControllers = List.generate(
      widget.texts.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 600),
        vsync: this,
      ),
    );

    _fadeInAnimations = _fadeInControllers.map((controller) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeInOut),
      );
    }).toList();

    _slideUpAnimations = _slideUpControllers.map((controller) {
      return Tween<Offset>(
        begin: const Offset(0, 1),
        end: Offset.zero,
      ).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeOutBack),
      );
    }).toList();

    _fadeOutAnimations = _fadeOutControllers.map((controller) {
      return Tween<double>(begin: 1.0, end: 0.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeInOut),
      );
    }).toList();

    _slideOutAnimations = _fadeOutControllers.map((controller) {
      return Tween<Offset>(
        begin: Offset.zero,
        end: const Offset(0, -1),
      ).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeInBack),
      );
    }).toList();

    _rotationAnimations = _slideUpControllers.map((controller) {
      return Tween<double>(
        begin: 1.0,
        end: 0.0,
      ).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeOutBack),
      );
    }).toList();
  }

  void _generateRandomPositions() {
    // 首先计算理想情况下的文字尺寸
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
      text: TextSpan(
        text: "测",  // 使用一个标准汉字来估算尺寸
        style: TextStyle(fontSize: widget.maxFontSize),
      ),
    )..layout();
    final maxCharWidth = textPainter.width;
    final maxCharHeight = textPainter.height;

    // 计算最小所需高度（使用最小字体大小和最小间距）
    final minTextPainter = TextPainter(
      textDirection: TextDirection.ltr,
      text: TextSpan(
        text: "测",
        style: TextStyle(fontSize: widget.minFontSize),
      ),
    )..layout();
    final minCharHeight = minTextPainter.height;
    final minSpacing = minCharHeight * 0.1;
    final minRequiredHeight = (minCharHeight * widget.texts.length) + 
                            (minSpacing * (widget.texts.length - 1));

    // 如果容器高度小于最小所需高度，使用最小配置
    final bool needsMinimumConfiguration = widget.containerHeight <= minRequiredHeight;

    // 计算实际使用的字体大小
    double actualMaxFontSize;
    if (needsMinimumConfiguration) {
      actualMaxFontSize = widget.minFontSize;
    } else {
      // 根据容器高度计算可用的最大字体大小
      final scale = widget.containerHeight / (maxCharHeight * widget.texts.length + 
                   (maxCharHeight * 0.1 * (widget.texts.length - 1)));
      actualMaxFontSize = (widget.maxFontSize * scale).clamp(
        widget.minFontSize,
        widget.maxFontSize
      );
    }

    // 使用实际字体大小重新计算字符高度
    final actualTextPainter = TextPainter(
      textDirection: TextDirection.ltr,
      text: TextSpan(
        text: "测",
        style: TextStyle(fontSize: actualMaxFontSize),
      ),
    )..layout();
    final actualCharHeight = actualTextPainter.height;
    final actualCharWidth = actualTextPainter.width;

    // 计算水平位置（考虑字符宽度，确保完全可见）
    _horizontalPositions = List.generate(
      widget.texts.length,
      (index) => _random.nextDouble() * (widget.containerWidth - actualCharWidth),
    );

    // 计算所需的总高度
    final totalRequiredHeight = actualCharHeight * widget.texts.length;
    
    // 计算可用于间距的空间
    final availableSpaceForSpacing = widget.containerHeight - totalRequiredHeight;
    
    // 计算每个间距的大小
    final numberOfSpaces = widget.texts.length - 1;
    final spacing = numberOfSpaces > 0 ? (availableSpaceForSpacing / numberOfSpaces).clamp(
      actualCharHeight * 0.1, // 最小间距
      actualCharHeight * 0.3  // 减小最大间距以节省空间
    ) : 0.0;

    // 计算第一个文字的起始位置，确保整体垂直居中
    final totalContentHeight = totalRequiredHeight + (spacing * numberOfSpaces);
    final startY = (widget.containerHeight - totalContentHeight) / 2;

    // 使用固定间距
    _verticalSpacings = List.filled(numberOfSpaces, spacing);

    // 计算每个文字的最终垂直位置
    _finalVerticalPositions = [];
    double currentY = startY;
    for (int i = 0; i < widget.texts.length; i++) {
      _finalVerticalPositions.add(currentY);
      if (i < widget.texts.length - 1) {
        currentY += actualCharHeight + spacing;
      }
    }

    // 根据实际可用空间生成随机字体大小
    final fontSizeRange = actualMaxFontSize - widget.minFontSize;
    _fontSizes = List.generate(
      widget.texts.length,
      (index) => widget.minFontSize + _random.nextDouble() * fontSizeRange,
    );

    // 当空间极其有限时，减小旋转角度范围
    final rotationRange = needsMinimumConfiguration ? 45.0 : 180.0;
    _initialRotations = List.generate(
      widget.texts.length,
      (index) => widget.enableRotation ? (_random.nextDouble() * rotationRange * 2 - rotationRange) : 0.0,
    );
  }

  void _startAnimation() async {
    do {
      if (_isDisposed) break;
      
      // 重置所有动画控制器
      setState(() {
        _isResetting = true;
        _isAnimatingIn = false;
        _isWaiting = false;
        _isAnimatingOut = false;
      });
      
      _resetAnimations();
      
      // 重新生成随机位置（每次循环都不同）
      if (widget.isLoop) {
        _generateRandomPositions();
      }

      // 短暂延迟确保重置完成
      await Future.delayed(Duration(milliseconds: 100));

      if (_isDisposed) break;
      setState(() {
        _isResetting = false;
        _isAnimatingIn = true;
        _shouldShow = true;
      });

      // 按顺序启动淡入动画，但有随机间隔
      for (int i = 0; i < widget.texts.length; i++) {
        if (_isDisposed) break;
        _fadeInControllers[i].forward();
        _slideUpControllers[i].forward();
        
        if (i < widget.texts.length - 1) {
          // 随机间隔 200-600ms
          await Future.delayed(
            Duration(milliseconds: 200 + _random.nextInt(400)),
          );
        }
      }

      if (_isDisposed) break;
      // 等待所有动画完成
      await Future.wait([
        ..._fadeInControllers.map((c) => c.isCompleted ? Future.value() : c.forward()),
        ..._slideUpControllers.map((c) => c.isCompleted ? Future.value() : c.forward()),
      ]);

      if (_isDisposed) break;
      setState(() {
        _isAnimatingIn = false;
        _isWaiting = true;
      });

      // 等待指定时间
      await Future.delayed(widget.waitDuration);

      if (_isDisposed) break;
      setState(() {
        _isWaiting = false;
        _isAnimatingOut = true;
      });

      // 随机顺序淡出
      List<int> indices = List.generate(widget.texts.length, (index) => index);
      indices.shuffle(_random);

      for (int index in indices) {
        if (_isDisposed) break;
        _fadeOutControllers[index].forward();
        
        // 随机间隔 100-400ms
        await Future.delayed(
          Duration(milliseconds: 100 + _random.nextInt(300)),
        );
      }

      if (_isDisposed) break;
      // 等待所有淡出动画完成
      await Future.wait(
        _fadeOutControllers.map((c) => c.isCompleted ? Future.value() : c.forward()),
      );

      if (_isDisposed) break;
      setState(() {
        _isAnimatingOut = false;
        _shouldShow = false;
      });

      widget.onAnimationComplete?.call();
      
      // 如果是循环模式，等待一小段时间后重新开始
      if (widget.isLoop && !_isDisposed) {
        await Future.delayed(widget.cyclePauseDuration ?? Duration.zero);
      }
    } while (widget.isLoop && !_isDisposed);
  }

  void _resetAnimations() {
    for (var controller in _fadeInControllers) {
      controller.reset();
    }
    for (var controller in _slideUpControllers) {
      controller.reset();
    }
    for (var controller in _fadeOutControllers) {
      controller.reset();
    }
  }

  @override
  void dispose() {
    _isDisposed = true;
    for (var controller in _fadeInControllers) {
      controller.dispose();
    }
    for (var controller in _slideUpControllers) {
      controller.dispose();
    }
    for (var controller in _fadeOutControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.containerHeight,
      width: widget.containerWidth,
      child: Stack(
        children: List.generate(widget.texts.length, (index) {
          return AnimatedBuilder(
            animation: Listenable.merge([
              _fadeInAnimations[index],
              _slideUpAnimations[index],
              _fadeOutAnimations[index],
              _slideOutAnimations[index],
              _rotationAnimations[index],
            ]),
            builder: (context, child) {
              // 如果不应该显示，完全隐藏元素
              if (!_shouldShow) {
                return const SizedBox.shrink();
              }
              
              double opacity = 0.0;
              Offset slideOffset = const Offset(0, 1);
              double rotationValue = 0.0;
              
              // 根据当前状态决定使用哪个动画的值
              if (_isAnimatingIn || _isWaiting) {
                // 淡入阶段或等待阶段，使用淡入动画的值
                opacity = _fadeInAnimations[index].value;
                slideOffset = _slideUpAnimations[index].value;
                rotationValue = _rotationAnimations[index].value;
              } else if (_isAnimatingOut) {
                // 淡出阶段，使用淡出动画的值
                opacity = _fadeOutAnimations[index].value;
                slideOffset = _slideOutAnimations[index].value;
                rotationValue = 0.0; // 淡出时不旋转
              }

              // 计算当前旋转角度
              double currentRotation = _initialRotations[index] * rotationValue;

              return Positioned(
                left: _horizontalPositions[index],
                top: _finalVerticalPositions[index],
                child: Transform.translate(
                  offset: Offset(
                    slideOffset.dx * 50,
                    slideOffset.dy * 50,
                  ),
                  child: Transform.rotate(
                    angle: currentRotation * (3.14159 / 180), // 转换为弧度
                    child: Opacity(
                      opacity: opacity,
                      child: Text(
                        widget.texts[index],
                        style: (widget.textStyle ?? const TextStyle()).copyWith(
                          fontSize: _fontSizes[index],
                          fontWeight: widget.textStyle?.fontWeight ?? FontWeight.w500,
                          color: widget.textStyle?.color ?? Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
              );
            },
          );
        }),
      ),
    );
  }
}